<template>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <strong>myself manage</strong>
        </el-breadcrumb-item>
        <el-breadcrumb-item>update selfInfo</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="info-box">
        <div class="avat-box">
            <el-avatar class="avatar" shape="square" :size="100" fit="cover" :src="avatarUrl" />
            <el-upload class="upload-demo" drag :http-request="()=>{}" :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpdate">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text" style="width:100%">
                    <strong>
                        Drop file here or <em>click to upload</em>
                    </strong> | 
                    <strong>jpg/png files with a size less than 1024kb</strong>
                </div>
            </el-upload>
        </div>  
        <el-divider />
        <div class="input-box">
            <div class="input-1">
                <p @click="infoTip('当前内容为登录时的账号,不可修改！！！')">登录账号：</p>
                <el-input v-model="userInfo.loginAccount" readonly placeholder="登录账号" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('登录密码，千万记住，修改密码时需要二次认证！！！')">登录密码：</p>
                <el-input v-model="password" placeholder="登录密码" size="large"></el-input>
            </div>
            <div class="input-1">
                <p @click="infoTip('账户状态 绿色为正常 ，红色为账户异常，异常时不可登录！！！')">账户状态：</p>
                <el-switch v-model="accountState" class="ml-2" disabled style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
            </div>
            <el-divider />
            <div class="input-1">
                <p @click="infoTip('当前用户姓名,请正确填写！！！')">姓名：</p>
                <el-input v-model="userInfo.userName"  placeholder="用户姓名" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('性别，只能填 男 或 女！！！')">性别：</p>
                <el-input v-model="userInfo.userSex" placeholder="用户性别 男/女" size="large" />
            </div>
             <div class="input-1">
                <p @click="infoTip('登录状态 绿色为正常 ，红色为登录异常，会强制下线！！！')">登录状态：</p>
                <el-switch v-model="loginState" class="ml-2" disabled style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
            </div>
            <div class="input-1">
                <p @click="infoTip('用户年龄，单位为岁，可填写虚岁，最小1岁，最大120岁！！！' )">年龄：</p>
                <el-input v-model.number="userInfo.userAge" placeholder="用户年龄 /岁" size="large" >
                    <template #append>岁</template>
                </el-input>
            </div>
            <div class="input-1">
                <p @click="infoTip('用户电话，支持手机号码，3-4位区号，7-8位直播号码，1－4位分机号！！！' )">电话：</p>
                <el-input v-model="userInfo.userPhone" placeholder="联系方式" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('用户是否是vip用户,vip用户功能更多，红色 表示非vip,绿色是vip' )">是否VIP：</p>
                <el-switch v-model="userInfo.isVip" class="ml-2" disabled style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
            </div>
            <div class="input-1">
                <p @click="infoTip('用户地址，请填写有效的地址！！！' )">地址：</p>
                <el-input v-model="userInfo.userAddress" placeholder="联系地址" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('用户登录方式，可登录的方式有：账号密码登录、手机短信登录(手机为完善个人信息的手机号码)、邮箱登录！！！' )">登录方式：</p>
                <el-input v-model="loginMode" readonly placeholder="账号 / 短信 / 邮箱" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('当前登录的有效期，在登录时选择，到达有效期后会自动强制退出！！！' )">登录有效期：</p>
                <el-input v-model="userInfo.loginValidityDay" readonly placeholder="登录有效期 1/24 h" size="large">
                    <template #append>小时</template>
                </el-input>
            </div>
            <div class="input-1">
                <p @click="infoTip('用户登录失败次数，到达失败次数后后锁定账户，过段时间自动解锁！！！' )">登录失败数：</p>
                <el-input v-model="userInfo.loginFailedCount" readonly placeholder="登录失败次数,最多失败8次" size="large" />
            </div>
            <div class="input-1">
                <p @click="infoTip('用户注册时间！！！' )">注册时间：</p>
                <el-input v-model="userInfo.regTime" readonly placeholder="注册时间" size="large" />
            </div>     
            <div class="input-1">
                <p @click="infoTip('用户登录时间！！！' )">登录时间：</p>
                <el-input v-model="userInfo.startLoginTime" readonly placeholder="开始登录时间" size="large" />
            </div>  
            <div class="input-1">
                <p @click="infoTip('用户爱好，可选择自己爱好！！！' )">爱好：</p>
                <el-select v-model="hobbiesVal"  multiple placeholder="选择爱好" style="width: 75%;">
                    <el-option v-for="item in hobbies" :key="item.id" :label="item.hobby" :value="item.hobby">
                        <el-tag class="mx-1" closable :type="item.type" effect="dark">
                            {{ item.hobby }}
                        </el-tag>
                    </el-option>
                </el-select>
            </div>
            <div class="input-1">
                <p @click="infoTip('用户描述，可对自己做简单的介绍！！！' )">描述：</p>
                <el-input v-model="userInfo.userDescribe" type="textarea" style="width:75%" rows="5" placeholder="用户描述为空,请添加描述信息" size="large" />
            </div>
        </div>
        <div class="btn-box">
            <el-button color="#626aef" :dark="isDark" @click="confirmUpdate">确认修改</el-button>
            <el-button color="#F56C6C" style="font-weight:500;color:white" :dark="isDark" @click="cancleUpdate">取消修改</el-button>
        </div>
    </div>
</template>

<script setup>
import { $http } from "@/utils/axios";
import { ElMessage, ElNotification } from "element-plus";
import { computed, onMounted, reactive, ref, watch } from "vue";
import {debounce, gatewayPrefix, userMiddleContextPath,currentUser,token, avatarUrlPrefix} from '@/utils/commConstance'
import { useDark } from '@vueuse/core'
import { UploadFilled } from '@element-plus/icons-vue'
import {planetSocket,getWsData} from '@/utils/socket'
const avatarUrl = ref('')
const isDark = ref(useDark())
const password = ref('********')
const input = ref('')
const loginValidityDay = ref('')
const loginMode = ref('')
const accountState = ref()
const loginState = ref()
const hobbiesVal = ref([])
const currentRoleId = ref()
// 先写死吧~~~
let hobbies = reactive([
    {"id":1,"hobby": '摔跤',"type": 'success'},
    {"id":2,"hobby": '射箭',"type": 'info'},
    {"id":3,"hobby": '骑马',"type": 'danger'},
    {"id":4,"hobby": '投壶',"type": 'warning'},
    {"id":5,"hobby": 'java',"type": ''}
])
onMounted(()=>{
    currentRoleId.value=sessionStorage.getItem("currentRole")
    if(currentRoleId.value !== undefined && currentRoleId.value !== null && currentRoleId.value !== ''){
        getMenusByRoleId()
        getCurrentUserInfo()
        // 获取websocket连接
        planetSocket()
    }else{
        // ElMessage.error('获取账号角色信息错误,请联系管理员!!!')
    }  
})
// 根据角色id获取菜单信息
const getMenusByRoleId = ()=>{
    let roleId = JSON.parse(currentRoleId.value)
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetMenus/getMenuInfoByRoleId/${roleId}`).then((res)=>{
        console.log('菜单信息===>',res);
    })
}
const infoTip = (tip) => {
    ElNotification({
        title: '文字说明',
        dangerouslyUseHTMLString: true,
        message: `<strong style='color: teal'>${tip}</strong>`,
        type: 'success',
    })
}
const user = JSON.parse(sessionStorage.getItem(currentUser));
let userInfo = reactive({})
//获取用户信息
const getCurrentUserInfo = ()=>{
    if(user == null){
        return ElMessage.warning('用户未登录,请登录')
    }
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/getCurrentUserInfo?account=`+user.loginAccount).then((res)=>{
        userInfo = reactive(res)
        avatarUrl.value = avatarUrlPrefix + userInfo.avatarName
        initUserInfo()
    }).catch((err) =>{
        console.log('getCurrentUserInfo error ==>',err);
        ElMessage.error(err.response || '获取用户信息失败,请联系管理员')
    })
}
//初始化
const initUserInfo = ()=>{
    password.value = '********'
    loginValidityDay.value = userInfo.loginValidityDay + '小时有效'
    if(userInfo.loginMode == 0){
        loginMode.value = '账号密码登录'
    }else if(userInfo.loginMode == 1){
        loginMode.value = '短信验证码登录'
    }else{
        loginMode.value = '邮箱登录'
    }

    if(userInfo.accountState == 0){
        accountState.value = true
    }else{
        accountState.value = false
    }

    if(userInfo.loginState == 0){
        //在线
        loginState.value = true
    }else{
        //离线
        loginState.value = false
    }
    //爱好 hobbiesVal
    hobbiesVal.value = userInfo.hobbies.split(',');

}
//上传头像回调
const beforeUpdate = (imgData)=>{
    const fileTypes = ['image/jpeg','image/jpg','image/png','image/webp']
    if(!fileTypes.includes(imgData.type)){
        return ElMessage.warning('上传图片格式错误,只能为 jpeg、jpg、png类型 ')
    }
    let fd = new FormData();
    fd.append("file",imgData)
    fd.append("fileType",imgData.type)
    $http.post(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/updateUserAvatar`,fd).then(res=>{
        ElMessage.success('上传成功')
        //目前头像显示根据url切割获取，后期可改成从数据库直接获取fileName即可
        let userPic = res
        let fileName = userPic.slice(userPic.lastIndexOf("/") + 1,userPic.length)
        avatarUrl.value = avatarUrlPrefix + fileName
    }).catch(err =>{
        console.log('upload err ==>',err);
        ElMessage.error(err.response.data.data.msg || '上传失败,请联系管理员')
    })
}
const uploadSuccess = (uploadData)=>{
    if(uploadData == 'ok'){
        
    }
}

//确认修改
const confirmUpdate = ()=>{
    userInfo.hobbies = hobbiesVal.value
    $http.post(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/updatePlanetUserInfo`,userInfo).then(res=>{
        ElMessage.success('修改成功')
        getCurrentUserInfo()
    }).catch(err =>{
        ElMessage.error(err.response.data.msg || '修改失败,请联系管理员')
    })
}
//取消修改
const cancleUpdate = ()=>{
    ElMessage.warning('放弃修改')
    userInfo = null
    getCurrentUserInfo()
}

</script>

<style src="../../assets/css/updateUserInfo.css"></style>